package com.itdct.onflow.system.generator.core

import com.itdct.onflow.com.itdct.onflow.system.generator.config.SysGeneratorConfig
import com.itdct.onflow.com.itdct.onflow.system.generator.context.SysGeneratorContext
import com.itdct.onflow.com.itdct.onflow.system.generator.util.JdbcHelper
import com.itdct.onflow.core.extend.logInfo
import com.itdct.onflow.generator.util.GeneratorLogUtil
import com.itdct.onflow.system.menu.entity.SysMenuEntity

/**
 * @author Zhouwx
 * @date 2025/9/8 15:55:10
 * @version 1.0
 * @description
 */
class SyncMenuCore() {
    fun syncMenu(context: SysGeneratorContext, generatorConfig: SysGeneratorConfig) {
        val sysMenuClassModel = context.sysMenuClassModel
        val connection = context.connection ?: return
        val classModel = context.classModel
        val className = classModel.className
        val packageName = classModel.packageName
        val groupId = generatorConfig.groupId
        if (groupId.isBlank()) {
            throw RuntimeException("groupId不能为空，请配置groupId，如：com.itdct.onflow")
        }

        if (!packageName.startsWith(groupId)) {
            throw RuntimeException("类${classModel.fullClassName}的packageName必须以groupId开头，如：com.itdct.onflow")
        }

        var path = packageName.substring(groupId.length + 1)
        path = path.replace(".", "/")
//        path = path.substring(0, path.lastIndexOf("/"))
        val pathRoutes = path.split("/")
        val parentIds = ArrayList<String>()

        // INFO: Zhouwx: 2025/9/8 插入字典的父菜单
        pathRoutes.filter { it.isNotBlank() }
            .forEachIndexed { index, pathRoute ->
                var sql: String
                if (index == 0) {
                    sql = "select * from sys_menu where name = '${pathRoute}' and parent_id = 0"
                } else {
                    sql = "select * from sys_menu where name = '${pathRoute}' and parent_id = '${parentIds[index - 1]}'"
                }

                val statement = connection.createStatement()
                val parentId = statement.executeQuery(sql).use {
                    if (it.next()) {
                        it.getString("id")
                    } else {
                        null
                    }
                }
                if (parentId != null) {
                    parentIds.add(parentId)
                } else {
                    val idPath = parentIds.joinToString("/")
                    // INFO: Zhouwx: 2025/8/27 模块的总目录，需要插入其中的值，以确保菜单的链是正确的
                    val bigMenu = JdbcHelper.selectList(connection, sysMenuClassModel, Pair(SysMenuEntity::name, className))
                    if (bigMenu.isEmpty()) {
                        val sysMenuEntity = SysMenuEntity()
                        sysMenuEntity.title = classModel.classUsage
                        sysMenuEntity.name = classModel.className
                        sysMenuEntity.parentId = parentIds.last().toLong()
                        sysMenuEntity.idPath = idPath
                        sysMenuEntity.orderNum = 1000
                        sysMenuEntity.enable = true
                        sysMenuEntity.canTo = true
                        sysMenuEntity.noPermission = false
                        sysMenuEntity.platformType = generatorConfig.platformType
                        val id = JdbcHelper.insert(connection, sysMenuClassModel, sysMenuEntity, {
                            GeneratorLogUtil.appendSql(it, context, generatorConfig)
                            it
                        })
                        parentIds.add(id.toString())
                    } else {
                        val sysMenuEntity = bigMenu.first()
                        parentIds.add(sysMenuEntity.id.toString())
                    }
                }
            }

        val parentSysMenuEntity = JdbcHelper.selectList(
            connection, sysMenuClassModel,
            Pair(SysMenuEntity::name, className),
            Pair(SysMenuEntity::id, parentIds.last().toLong())
        )
            .firstOrNull() ?: throw RuntimeException("类${classModel.fullClassName}对应的菜单不存在")
        val menuId = parentSysMenuEntity.id!!

        var componentPath = packageName.substring(groupId.length + 1)
        componentPath = componentPath.replace(".", "/")

        // INFO: Zhouwx: 2025/9/5 初始化单个页面，分别为Page、Add、Edit
        if (!queryMenuExist(context, menuId, "Page")) {
            insertSingleMenu(context, generatorConfig, componentPath, menuId, parentIds, "Page")
        } else {
            logInfo("${className}Page菜单已存在")
        }

        if (!queryMenuExist(context, menuId, "Add")) {
            insertSingleMenu(context, generatorConfig, componentPath, menuId, parentIds, "Add")
        } else {
            logInfo("${className}Add菜单已存在")
        }

        if (!queryMenuExist(context, menuId, "Edit")) {
            insertSingleMenu(context, generatorConfig, componentPath, menuId, parentIds, "Edit")
        } else {
            logInfo("${className}Edit菜单已存在")
        }
    }

    private fun insertSingleMenu(context: SysGeneratorContext, generatorConfig: SysGeneratorConfig, componentPath: String, menuId: Long, parentIds: ArrayList<String>, type: String) {
        val classModel = context.classModel
        val className = classModel.className
        val typeName = when (type) {
            "Page" -> ""
            "Add" -> "新增"
            "Edit" -> "编辑"
            else -> throw RuntimeException("未知的菜单类型")
        }
        val orderNum = when (type) {
            "Page" -> 10
            "Add" -> 11
            "Edit" -> 12
            else -> throw RuntimeException("未知的菜单类型")
        }
        val hiddenMenu = when (type) {
            "Page" -> false
            "Add" -> true
            "Edit" -> true
            else -> throw RuntimeException("未知的菜单类型")
        }

        val componentName = when (type) {
            "Page" -> "${className}Page"
            "Add" -> "${className}Edit"
            "Edit" -> "${className}Edit"
            else -> throw RuntimeException("未知的菜单类型")
        }
        if (!queryMenuExist(context, menuId, type)) {
            val sysMenuEntity = SysMenuEntity()
            sysMenuEntity.title = classModel.classUsage + typeName
            sysMenuEntity.name = className + type
            sysMenuEntity.component = "${componentPath}/${componentName}.vue"
            sysMenuEntity.parentId = menuId
            sysMenuEntity.idPath = parentIds.joinToString("/")
            sysMenuEntity.orderNum = orderNum
            sysMenuEntity.hiddenMenu = hiddenMenu
            sysMenuEntity.hiddenTag = false
            sysMenuEntity.enable = true
            sysMenuEntity.canTo = true
            sysMenuEntity.noPermission = false
            sysMenuEntity.platformType = generatorConfig.platformType
            val id = JdbcHelper.insert(context.connection!!, context.sysMenuClassModel, sysMenuEntity, {
                GeneratorLogUtil.appendSql(it, context, generatorConfig)
                it
            })
            sysMenuEntity.id = id
            when (type) {
                "Page" -> {
                    context.pageMenuId = id
                    context.pageMenuEntity = sysMenuEntity
                }

                "Add" -> {
                    context.addMenuId = id
                    context.addMenuEntity = sysMenuEntity
                }

                "Edit" -> {
                    context.editMenuId = id
                    context.editMenuEntity = sysMenuEntity
                }
            }
        } else {
            logInfo("${className}${type}菜单已存在")
        }
    }

    private fun queryMenuExist(context: SysGeneratorContext, menuId: Long, type: String): Boolean {
        val classModel = context.classModel
        val className = classModel.className
        val sysMenuEntities = JdbcHelper.selectList(context.connection!!, context.sysMenuClassModel, Pair(SysMenuEntity::name, className + type), Pair(SysMenuEntity::parentId, menuId))
        if (sysMenuEntities.isNotEmpty()) {
            return true
        } else {
            return false
        }
    }
}